<template>
  <div class="selector-menu">
    <template v-if="searchData.length > 0">
      <div
        class="menu-item"
        v-for="(item, index) of searchData"
        :key="index"
        @click="setItemValue(item)"
      >
        {{ item.text }}
      </div>
    </template>
    <no-data-tip v-else></no-data-tip>
  </div>
</template>

<script>
import NoDataTip from "./NoDataTip.vue";

export default {
  name: "SelectorMenu",
  components: {
    NoDataTip,
  },
  props: {
    data: {
      type: Array,
      default() {
        return [
          {
            id: 1,
            value: "1",
            text: "选项1",
          },
          {
            id: 2,
            value: "2",
            text: "选项2",
          },
          {
            id: 3,
            value: "3",
            text: "选项3",
          },
        ];
      },
    },
    //用户输入的文本内容
    searchValue: String,
  },
  data() {
    return {
      searchData: [],
    };
  },
  methods: {
    //点击列表中的某一项时
    setItemValue(item) {
      this.$emit("setItemValue", item);
    },
    //过滤数据
    filterData(value) {
      this.searchData = this.data.filter((item) => {
        return item.text.toLowerCase().includes(value.toLowerCase());
      });
    },
  },
  //组件挂载之前时
  beforeMount() {
    //将用户编写的列表数组存入当前组件searchData数组
    this.searchData = this.data;
  },
  watch: {
    searchValue(newValue, oldValue) {
      // console.log(oldValue);
      this.filterData(newValue);
    },
  },
};
</script>

<style lang="scss" scoped>
.selector-menu {
  display: none;
  position: absolute;
  left: 0;
  top: 48px;
  width: 100%;
  background-color: #fff;
  box-shadow: 0 0 10px #ddd;
  border-radius: 5px;
  cursor: pointer;

  .menu-item {
    height: 35px;
    text-align: center;
    line-height: 35px;
    font-size: 14px;
    color: #666;
    margin: 10px 0;
    transition: background-color 0.2s linear;

    &:hover {
      background-color: #ededed;
    }
  }
}
</style>
